<?php

namespace fakis\core\traits;

use fakis\core\base\DefineModel;
use fakis\core\base\DefineProp;

/**
 * 连接定义模型
 *
 * ```php
 * public function getSetting()
 * {
 *     return $this->linkOne('data', [
 *         'name' => DefineProp::TYPE_STRING,
 *         'price' => DefineProp::TYPE_NUMBER,
 *         'stock' => DefineProp::TYPE_INTEGER,
 *         'active' => DefineProp::TYPE_BOOLEAN,
 *     ]);
 * }
 * ```
 *
 * @author Fakis <fakis738@qq.com>
 */
trait ModelLink
{
    /**
     * 连接单个定义模型
     * @param string $attribute
     * @param array|DefineProp[] $props
     * @return DefineModel
     * @throws \yii\base\InvalidConfigException
     */
    public function linkOne($attribute, $props)
    {
        $data = $this->$attribute;
        $model = new DefineModel($props);
        $model->load($data);
        return $model;
    }

    /**
     * 连接多个定义模型
     * @param string $attribute
     * @param array|DefineProp[] $props
     * @return DefineModel[]
     * @throws \yii\base\InvalidConfigException
     */
    public function linkMany($attribute, $props)
    {
        $result = [];
        $data = $this->$attribute;
        foreach ((array)$data as $datum) {
            $model = new DefineModel($props);
            $model->load($datum);
            $result[] = $model;
        }
        return $result;
    }
}